import * as echarts from '../../ec-canvas/echarts';
var baseConfig = require("../../baseConfig")
const app = getApp();

function initChart1(chart, xdata, ydata) {

  var option = {
    title: {
      text: '',
      left: 'center',
    },
    color: ["#fff"],
    legend: {
      data: ['A'],
      top: 50,
      left: 'center',
      z: 100
    },
    grid: {
      containLabel: true
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,

      data: xdata,
      minorSplitLine: {
        show: true,
        lineStyle: {
          color: '#ddd'
        }
      },
      axisLabel: {
        color: "#fff"
      },
      axisLine: {
        lineStyle: {
          color: "#fff"
        }
      }
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLabel: {
        color: "#fff"
      },
      axisLine: {
        lineStyle: {
          color: "#fff"
        }
      }
    },
    dataZoom: [{
      show: true,
      type: 'inside',
      filterMode: 'none',
      xAxisIndex: [0],
      startValue: 0,
      endValue: 15
    }, ],
    series: [{
      type: 'line',
      data: ydata
    }]
  };

  chart.setOption(option);
}

function initChart2(chart, xdata, ydata) {

  var option = {
    title: {
      text: '',
      left: 'center',
    },
    color: ["#fff"],
    legend: {
      data: ['A'],
      top: 50,
      left: 'center',
      z: 100
    },
    grid: {
      containLabel: true
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xdata,
      minorSplitLine: {
        show: true,
        lineStyle: {
          color: '#ddd'
        }
      },
      axisLabel: {
        color: "#fff"
      },
      axisLine: {
        lineStyle: {
          color: "#fff"
        }
      }
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLabel: {
        color: "#fff"
      },
      axisLine: {
        lineStyle: {
          color: "#fff"
        }
      }
    },
    dataZoom: [{
      show: true,
      type: 'inside',
      filterMode: 'none',
      xAxisIndex: [0],
      startValue: 0,
      endValue: 15
    }, ],
    series: [{
      type: 'line',
      data: ydata
    }]
  };

  chart.setOption(option);
}

const formatNumber = (n) => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function formatTimeTwo(number, format) {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}

Page({
  data: {
    is_weixin: 0,
    selectTime: formatTimeTwo(Date.parse(new Date()), 'Y-M-D'),
    date: formatTimeTwo(Date.parse(new Date()), 'Y-M-D'),
    show: false,
    ec1: {
      lazyLoad: true
    },
    ec2: {
      lazyLoad: true
    },
    minDate: new Date().getTime() - 24 * 60 * 60 * 1000 * (formatTimeTwo(Date.parse(new Date()), 'Y-M-D').split("-")[2] - 1),
    maxDate: new Date().getTime(),

    // array1: ['抖音', '微信'],
    array1: ['抖音'],
    index1: 0,
    array2: [],
    index2: 0,

    earningsDataSumMap: {},
    earningsDataMap: {},
    ecpmDataMap: {},

    layer1Popup: false,
    layer2Popup: false,
    layer3Popup: false,
    layer4Popup: false,
    layer5Popup: false,
    layer6Popup: false,
    layer7Popup: false,
  },
  onLoad: function (options) {
    this.getProductId()
  },
  onReady: function () {
    // this.getDataMocks()
    this.oneComponent = this.selectComponent('#mychart-one');
    this.twoComponent = this.selectComponent('#mychart-two');
    // console.log('oneComponent111111111111111111', this.oneComponent);
    // console.log('twoComponent111111111111111111', this.twoComponent);
  },
  onShow: function () {
    this.setData({
      // index1: 0,
      // index2: 0,
      date: this.data.selectTime
    })
    // 优化-为未登录状态下进行跳转
    // let isVip = wx.getStorageSync('userInfo').role
    // if (isVip == undefined || isVip == null) {
    //   console.log('未登录');
    //   wx.showToast({
    //     icon: "loading",
    //     title: "请先登录",
    //     duration: 1000
    //   })
    //   setTimeout(() => {
    //     wx.switchTab({
    //       url: "/pages/me/me"
    //     })
    //   }, 1000)
    // } else if (isVip == 'USER') {
    //   console.log('会员');
    // } else {
    //   console.log('非会员');
    //   wx.showModal({
    //     title: '提示',
    //     content: '请先激活会员',
    //     showCancel: false,
    //     success(res) {
    //       if (res.confirm) {
    //         wx.switchTab({
    //           url: "../me/me"
    //         });
    //       }
    //     }
    //   })
    // }
  },
  toProfitInfo(e) {
    // console.log('profitDetails', e.currentTarget.dataset);
    let {
      appid,
      appname
    } = e.currentTarget.dataset
    // console.log(appid, appname);
    wx.navigateTo({
      url: '/pages/profitInfo/profitInfo?appId=' + appid +
        '&appName=' + appname +
        '&date=' + this.data.date
    })
  },
  reloadClick() {
    this.getProductId()
    this.getDataMocks()
  },
  selectPlatForm(e) {
    this.setData({
      index1: e.detail.value
    })
    this.getProductId()
  },
  selectProduct(e) {
    this.setData({
      index2: e.detail.value
    })
    this.getProductId()
  },
  selectTimeClick(e) {
    this.setData({
      date: e.detail.value
    })
    console.log(this.data.date);
    this.getDataMocks()
  },
  formatDate(date) {
    date = new Date(date);
    var year = `${date.getFullYear()}`
    var month = `${date.getMonth() + 1}`
    var dated = `${date.getDate()}`
    if (month < 10) {
      month = "0" + month
    }
    if (dated < 10) {
      dated = "0" + dated
    }
    return `${year}-${month}-${dated}`;
  },
  
  init_one(xdata, ydata) { //初始化第一个图表
    this.oneComponent.init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      // console.log(chart)
      // console.log(xdata)
      // console.log(ydata)
      initChart1(chart, xdata, ydata)
      this.chart = chart;
      return chart;
    });
  },
  init_two(xdata, ydata) { //初始化第二个图表
    this.twoComponent.init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      initChart2(chart, xdata, ydata)
      this.chart = chart;
      return chart;
    });
  },
  getProductId() {
    wx.request({
      url: `${baseConfig.url}baseSelect/mini_app_select`,
      method: 'POST',
      data: {
        is_weixin: this.data.index1 //"1":微信   "0":抖音
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        console.log(res.data.data);
        this.setData({
          array2: res.data.data
        })
        // console.log(this.data.array2[this.data.index2].value)
        this.setData({
          appId: this.data.array2[this.data.index2].value,
          appName: this.data.array2[this.data.index2].name
        })
        console.log(111);
        this.getDataMocks()
        console.log(this.data.appId);
        if (this.data.appId == '28') {
          this.setData({
            appType: 'cpm'
          })
        } else if (this.data.appId == '29') {
          this.setData({
            appType: 'cps'
          })
        }
        console.log(this.data.appType);
      }
    })
  },
  getDataMocks() {
    var openid = wx.getStorageSync('openid')
    // console.log("openid11111111:",openid)
    var uid = wx.getStorageSync("userid")
    if (openid != undefined) {
      wx.request({
        url: `${baseConfig.url}tuiwaApp/get_earnings_data_sum`,
        method: 'POST',
        data: {
          start_time: this.data.date,
          end_time: this.data.selectTime,
          appId: this.data.appId,
          loginUserId: openid,
          uid: uid,
          is_weixin: this.data.index1, //"1":微信   "0":抖音
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: res => {
          this.setData({
            earningsDataSumMap: res.data.data.earningsDataSumMap,
            earningsDataMap: res.data.data.earningsDataMap,
            ecpmDataMap: res.data.data.ecpmDataMap
          })
          console.log('earningsDataSumMap', this.data.earningsDataSumMap);
          var initChart1OptionXAxisData = res.data.data.earningsDataMap.earningsDateList
          var initChart1OptionSeriesData = res.data.data.earningsDataMap.earningsValueList
          this.init_one(initChart1OptionXAxisData, initChart1OptionSeriesData)

          var initChart2OptionXAxisData = res.data.data.ecpmDataMap.ecpmDateList
          var initChart2OptionSeriesData = res.data.data.ecpmDataMap.ecpmValueList
          this.init_two(initChart2OptionXAxisData, initChart2OptionSeriesData)
        }
      })
    }
  },
  CPMClick() {
    this.setData({
      layer1Popup: true
    })
  },
  CPMClick1() {
    this.setData({
      layer5Popup: true
    })
  },
  closeClick1() {
    this.setData({
      layer1Popup: false,
      layer5Popup: false,
    })
  },
  adClick() {
    this.setData({
      layer2Popup: true
    })
  },
  closeClick2() {
    this.setData({
      layer2Popup: false
    })
  },
  ecpmClick() {
    this.setData({
      layer3Popup: true
    })
  },
  closeClick3() {
    this.setData({
      layer3Popup: false
    })
  },
  yesClick() {
    this.setData({
      layer4Popup: true
    })
  },
  yesClick1() {
    this.setData({
      layer6Popup: true
    })
  },
  closeYesClick() {
    this.setData({
      layer4Popup: false,
      layer6Popup: false,
      layer7Popup: false,
    })
  },
  yesClick2() {
    this.setData({
      layer7Popup: true
    })
  },
})